<?php
/**
 * 会员中心管理
 * @author cjli
 *
 */ 
class UserAction extends HomeAction
{

	public function _initialize()
	{
		parent::_initialize();
		global $user;
		if(isset($user['is_partner']) && $user['is_partner'] == 1){
		    redirect(url('partner/center'));
		}
	} 
	 
	public function index()
	{
		$this->center();
	}
	
	//会员登录
	public function login()
	{
		global $user;
		$data = array(
    		'docTitle' => L('meta_title_login'),
    		'docKeywords' => L('meta_keywords'),
    		'docDescription' => L('meta_description'),
    	);
		$this->assign($data);
		$post = $_REQUEST;
		$src = isset($post['src']) ? trim($post['src']) : null;
        $action=   isset($post['action']) ? trim($post['action']) : null;
		$this->assign('src', $src);
		//跳转到上一个页面
		$http = $_SERVER['HTTP_REFERER'];
		$this->assign('http',$http);
        $this->assign('action',$_GET['action']);
		$src_login = strstr(base64_decode($src), 'measure/cart');
		$this->assign('src_login', $src_login);
		$this->assign('facebookLoginUrl',$this->facebook_login());
		if(UserModel::logged())
		{
            if($action=="measure"){
                redirect(url('measure/measure'));
            } else {
                redirect($src ? base64_decode($src) : url('user/center'));
            }
		}
		elseif(isset($post['dosubmit']))
		{
			$this->assign('jumpUrl', url('user/login', array('src' => $src ? $src : null)));

			if(C('vcode_login') == 1 && isset($post['login_vcode'])){
				if($_SESSION['login_vcode'] != strtolower($post['login_vcode'])){
					$this->error(L('_VERIFICATION_ERROR_'));
				}
			}
			
			$username = trim($post['username']);
			$password = trim($post['password']);
			$goback = $post['goback'];
			//登录验证
			if(!$user_id = UserModel::validate_user($username, $password)){
				$this->error(L('_LOGIN_FAILED_THE_USER_NAME_OR_PASSWORD_ERROR_'));
			}

			//获取用户信息
			$user_info = UserModel::get_user_info($user_id);
			if(!$user_info['disabled']){
				$this->error(L('_MEMBER_ACCOUNT_HAS_BEEN_DISABLED_PLEASE_CONTACT_YOUR_ADMINISTRATOR_'));
			}
			session('user_id', $user_id);
			
			//更新用户数据
			UserModel::setLogin($user_id);

			//合并购物车
			CartModel::mergeCart($user['sid']);

			//合并浏览记录
			ProductModel::mergeBrowsingHistory($user['sid']);			
			
			//合并身型数据
			AttributeModel::mergeMeasure($user['sid']);
            
			//删除游客登陆
			session('countiue_buy', null);
			if($src){
                redirect(base64_decode($src));
			}else if($goback){
				redirect($goback);
			}else{
				redirect($http);
			}
		}else{
			$this->display('login');
		}
	}
	
    public function update_order(){
        global $user,$language_id;
        $order_id = intval($_GET['oid']);
        if(IS_POST && $order_id){

            if($_POST['surplus_money'] > 0){
                $surplus_money = isset($_POST['surplus_money']) ? floatval($_POST['surplus_money']) : 0;
                $currency = isset($_SESSION['currency']) ? $_SESSION['currency'] : C('currency');

                //如果使用余额小于会员余额
                if($user && isset($user['user_money']) && $user['user_money']>0){
                    $surplus_money = $user['user_money']<$surplus_money ? $user['user_money'] : $surplus_money;
                }else{
                    $surplus_money = 0;
                }
                $order_info = M('orders')->where('id ='.$order_id.' and user_id ='.$user['id'])->find();

                //扣除会员的余额
                if($surplus_money && $user['id']){
                    UserModel::log_account_change($user['id'],(-1)*$surplus_money,0,0,0,L('_ORDER_USE_BALANCE_PAYMENT_').' '.L('_THE_ORDER_NUMBER_IS_').' '.$order_info['order_sn'],UserModel::ACT_PAY);
                }
                $pay_amount = $order_info['pay_amount'] - $surplus_money;
                if($order_info['surplus_money'] > 0){//之前使用过余额下单 再次使用余额支付
                    $surplus_money = $order_info['surplus_money'] + $surplus_money;
                }
                $data = array(//更新订单状态
                    'id'=> $order_id,
                    'surplus_money' => $surplus_money,
                    'pay_amount'  => $pay_amount,
                    'currency'  => $currency,
                    'language_id'  => $language_id,
                );
                if($pay_amount ==  0){//全部余额支付
                	    //支付通知短信
                        $ShortMessage=A("ShortMessage");
                        $result2=$ShortMessage->send_message('SMS_4725607',$order_info['delivery_phone'],'{"order_sn":"'.$order_info['order_sn'].'"}');
                      //  if($result2){
                            Log::write('支付短信，订单号'.$order_info['order_sn'].'，全部余额支付，订单金额：'.$order_info['order_amount'].'，时间：'.date("Y-m-d H:i:s",time()));
                      //  }
                     //判断是否使用优惠码  反给推荐人余额
                       if($order_info['coupon_code']&&$order_info['product_amount']>=399) {
                           UserModel::get_money_friend($order_info['coupon_code']);
                       }
                        $data['payment_status'] = OrderModel::PAY_PAYED;
                        $data['order_status'] = OrderModel::ORDER_CONFIRMED;
                        $data['payment_time'] = time();
                        OrderModel::gift_email($order_id);//giftcard发送邮件
                }
                if($surplus_money > 0){
                        M('orders')->save($data);
                }
            }
            $data = array(//更新订单支付方式
                'id'=> $order_id,
                'payment_method'  => $_POST['payment_method'],
            );
            M('orders')->save($data);
            redirect(url('cart/ordersuccee', 'oid='.$order_id));
        }
    }
	//会员登录
	public function login_ajax()
	{
		global $user;
		
		$post = $_REQUEST;
		
		$result = array(
			'error' => 1,
			'message' => '',
		);
		
		if(UserModel::logged()){
				$result['error'] = 0;
				$result['message'] = L('_LOGINED_SUCCESS_');
		}else{
			
			
			$username = trim($post['username']);
			$password = trim($post['password']);
			$login_vcode = strtolower($post['login_vcode']);
			
			if(C('vcode_login') == 1){
				if($_SESSION['login_vcode'] != $login_vcode){
					$result = array(
						'error' => 1,
						'message' => L('_VERIFICATION_ERROR_'),
					);
					echo json_encode($result);exit;
				}
			}
			
			if( !$user_id = UserModel::validate_user($username, $password) ){
				$result['message'] = L('_LOGIN_FAILED_THE_USER_NAME_OR_PASSWORD_ERROR_');
			}else{
				$user_info = UserModel::get_user_info($user_id);
				if(!$user_info['disabled']){
					$result['message'] = L('_MEMBER_ACCOUNT_HAS_BEEN_DISABLED_PLEASE_CONTACT_YOUR_ADMINISTRATOR_');
				}else{
					$result['error'] = 0;
					$result['message'] = L('_LOGINED_SUCCESS_');
				}
				session('user_id', $user_id);
				//更新用户数据
				UserModel::setLogin($user_id);
				//合并购物车
				CartModel::mergeCart($user['sid']);
				//合并浏览记录
				ProductModel::mergeBrowsingHistory($user['sid']);					
				//合并身型数据
				AttributeModel::mergeMeasure($user['sid']);				
			}
		}
		echo json_encode($result);exit;
	}
	
	//会员注册
	public function register()
	{
		global $user, $language_id;
		$post =$_REQUEST;
		$post['username'] = $post['phone'];
		$data = array(
    		'docTitle' => L('meta_title_register'),
    		'docKeywords' => L('meta_keywords'),
    		'docDescription' => L('meta_description'),
    	);
		$this->assign($data);
		$src = isset($post['src']) ? trim($post['src']) : null;
        $action=   isset($post['action']) ? trim($post['action']) : null;
		$this->assign('src', $src);		
		$src_login = strstr(base64_decode($src), 'measure/cart');
		$this->assign('src_login', $src_login);		
		if(UserModel::logged())
		{
			redirect($src ? base64_decode($src) : url('product/all'));
		}
		elseif(isset($_POST['dosubmit']))
		{
			global $language_id;
			
			$this->assign('jumpUrl', url('user/register', array('src' => $src ? base64_decode($src) : null)));
			
			if(C('vcode_register') == 1 && isset($post['register_vcode'])){
				if($_SESSION['register_vcode'] != strtolower($post['register_vcode'])){
					$this->error(L('_VERIFICATION_ERROR_'));
				}
			}
			
			if(isset($_POST['agree_true']) && intval($post['agree_true']) != 1){
				$this->error(L('_PLEASE_CAREFULLY_READ_THE_TERMS_AND_CONDITIONS_'));
			}
			
			import('COM.Validate');
			if(empty($post['username']) || !Validate::registerPhone($post['username'])){
				$this->error(L('_PHONE_FORMAT_ERROR_'));
			}			
			if(empty($post['email']) || !Validate::email($post['email'])){
				$this->error(L('_EMAIL_FORMAT_ERROR_'));
			}
			if(empty($post['password']) || (! Validate::len($post['password'],6,20))){
				$this->error(L('_THE_PASSWORD_SHOULD_BE_BETWEEN_6_20_'));
			}
			if($post['confirm_password'] != $post['password']){
				$this->error(L('_ENTER_THE_PASSWORD_TWICE_INCONSISTENT_'));
			}
			if(isset($post['username']) && UserModel::validate_username_only($post['username'])){
				$this->error(L('_phone_registered_'));
			}
			if(UserModel::validate_email_only($post['email'])){
				$this->error(L('_EMAIL_ALREADY_EXISTS_'));
			}

			if(!$user_id = UserModel::insert_user($post)){
				$this->error(L('_REGISTRATION_FAILED_'));
			}else{
				session('user_id', $user_id);
				//用户注册送红包 2015-01-19起取消注册赠送红包
				//UserModel::user_bonus('register',$user_id); 
				//用户注册赠送余额 $20
/*				UserModel::user_account_change($user_id, 20, 0, 1, NULL, 'register', NULL);
				UserModel::log_account_change($user_id, 20, 0, 0 ,0, 'register', UserModel::ACT_SAVING);*/
				//填写问卷送红包
				if(session('survey') !='')
				{ 	
					UserModel::user_bonus('survey',$user_id); 
					session('survey',null);
				}
				if(isset($post['is_email']) && $post['is_email']){
					//UserModel::update_email_registory($post['email']);
					MeasureModel::add_subscriptions_info($post['email']);  					
				}
				
				//合并购物车
				CartModel::mergeCart($user['sid']);
				//合并浏览记录
				ProductModel::mergeBrowsingHistory($user['sid']);	
				//合并身型数据
				AttributeModel::mergeMeasure($user['sid']);
				
				/*//注册通知邮件
				$email_template = UserModel::get_email_template_info('userRegisterEmail', $language_id);
				if($email_template){
					$content = str_replace('{$user_name}', $username, $email_template['content']);
					$content = str_replace('{$user_email}', $post['email'], $content);
					$mailInstance = new EmailModel();
					$content = $mailInstance->replaceMail($content);
					$title = $mailInstance->replaceMail($email_template['title']);
					$mailInstance->sendMail($post['email'], $title, $content);
				}*/
                //注册通知短信
                $ShortMessage=A("ShortMessage");
                $str_short_message='{"username":"'.$post['email'].'","password":"'.$post['password'].'","ownonly":"ownonly.net"}';
                $short_mesg_result=$ShortMessage->send_message("SMS_4740514",$post['username'],$str_short_message);
                if($short_mesg_result){
                    Log::write('注册短信，邮箱：'.$post['email'].'，时间：'.date("Y-m-d H:i:s",time()));
                }
                //判断是否使用优惠码  反给推荐人余额
                UserModel::get_money_friend(null,$post['username']);
                if($action=="measure"){
                    redirect(url('measure/measure'));
                }else {
                    $this->success(L('registory_success'), $src ? base64_decode($src) : url('product/all'));
                }
			}
		}else{
			$this->assign('facebookLoginUrl',$this->facebook_login());
			$this->display('register');
		}
	}
	
	
	public function register_success()
	{
		$this->display('register_success');
	}
	
	//找回密码
	public function getpassword()
	{
		global $language_id;
		$data = array(
    		'docTitle' => L('meta_title_getpassword'),
    		'docKeywords' => L('meta_keywords'),
    		'docDescription' => L('meta_description'),
    	);
		$this->assign($data);
		if($_POST['dosubmit']){
			
			if(C('vcode_password') == 1 && isset($_POST['password_vcode'])){
				if($_SESSION['password_vcode'] != strtolower($_POST['password_vcode'])){
					$this->error(L('_VERIFICATION_ERROR_'));
				}
			}
			
//			$username = trim($_POST['username']);
			$email = trim($_POST['email']);
			$userInfo = UserModel::get_user_info_by_other(array('email' => $email));
			if(!$userInfo){
				$this->error(L('_USER_NAME_AND_EMAIL_INCONSISTENCY_'), url('user/getpassword'));
			}else{
				//发送验证码到邮箱
				$email_template = UserModel::get_email_template_info('getPasswordEmail', $language_id);
				if($email_template){
					import('ORG.Util.String');
					$token = String::randString(16);
					$content = str_replace('{$user_name}', $email, $email_template['content']);
					$src = base64_encode($email.'###'.$token);
					$content = str_replace('{$url}', url('user/editpassword', 'src='.$src), $content);
					$mailInstance = new EmailModel();
					$content = $mailInstance->replaceMail($content);
					$title = $mailInstance->replaceMail($email_template['title']);
					if($mailInstance->sendMail_direct($email, $title, $content)){
						//保存到数据库
						$user_db = D('users');
						$set = array(
							'token' => $token,
							'time' =>	time(),
						);
						$set = array_merge($userInfo['data'], $set);
						$user_db->where(array('id' => $userInfo['id']))->save(array('data' => serialize($set)));
						$this->success(L('_EMAIL_SENT_SUCCESSFULLY_'));
					}else{
						$this->error(L('_EMAIL_SENT_FAILURE_'));
					}
				}
			}
		}else{
			$this->display('getpassword');
		}
	}
	
	//找回密码跳转修改
	public function editpassword()
	{
		$src = $_REQUEST['src'];
		if(empty($src)){
			redirect(url('user/getpassword'),'', L('_ERROR_ACTION_'));
		}
			$src_data = base64_decode($src);
			$src_data = explode('###', base64_decode($src));
			$email = $src_data[0];
			$token = $src_data[1];
			
			$userInfo = UserModel::get_user_info_by_other(array('email' => $email));
//			dump($userInfo);exit;
			if(!$userInfo){
				$this->error(L('_USER_NOT_EXIST_'), url('user/register'));
			}
			if($userInfo['data'] && isset($userInfo['data']['token'])){
				if($userInfo['data']['token'] != $token  && (time()-$userInfo['data']['time'])> 43200){
					$this->error(L('_VALIDATION_EXPIRED_'), url('user/getpassword'));
				}
			}else{
				$this->error(L('_ILLEGAL_OPERATION_'), url(''));
			}
			
		if(isset($_POST['dosubmit'])){
			$password = $_POST['password'];
			import('COM.Validate');
			$validate = new Validate();
			if(empty($password) || !$validate->len($password,6,20)){
				$this->error(L('_THE_PASSWORD_SHOULD_BE_BETWEEN_6_20_'));
			}
			if(empty($_POST['confirm_password']) || $_POST['confirm_password'] != $password){
				$this->error(L('_ENTER_THE_PASSWORD_TWICE_INCONSISTENT_'));
			}
			
			//用户data字段中的token和时间
			if($userInfo['data']){
				unset($userInfo['data']['token']);
				unset($userInfo['data']['time']);
			}
			
			$data = array(
				'password' => $password,
				'data' => $userInfo['data'],
				'login_count' => $userInfo['login_count']+1,
			);
			if(UserModel::update_user($userInfo['id'], $data)){
				session('user_id', $userInfo['id']);
				$this->success(L('_PASSWORD_EDIT_SUCCESS_'), url('user/center'));
			}else{
				$this->error(L('_PASSWORD_EDIT_FAILED_'));
			}
		}else{
			
			$data = array(
				'email' => $email,
				'token' => $token,
				'submit_url' => url('user/editpassword', array('src' =>  base64_encode($email.'###'.$token))),
			);
			$this->assign($data);
			$this->display('editpassword');
		}
	}
	
	//会员登出
	public function logout()
	{
		UserModel::logout();
		$post = $_REQUEST;
		$src = isset($post['src']) ? trim($post['src']) : null;
		if($src){
            redirect(base64_decode($src));
		}else{
			redirect(url(''));
		}
	}
	
	public function user_safe()
	{
		global $user;
		$data = array(
			'docTitle' => L('meta_title_user_safe'),
			'docKeywords' => L('meta_keywords'),
			'docDescription' => L('meta_description'),
		);
		$this->assign($data);
		//$this->checklogin();
		if(UserModel::logged()){
		$_SESSION['center_type'] = 8;
		$templatefile = THEMES_PATH.'user/user_safe.phtml';
		$this->assign('templatefile', $templatefile);
		}else{
		$templatefile = THEMES_PATH.'user/user_login.phtml';
		$this->assign('templatefile', $templatefile);			
		}
		$this->display('usercenter');
	}
	
	//邮箱认证
	public function validate_email()
	{
		global $user, $language_id;
		$this->checklogin();
		
		$email = $user['email'];
		
	//发送验证码到邮箱
				$email_template = UserModel::get_email_template_info('validateEmail', $language_id);
				if($email_template){
					import('ORG.Util.String');
					$token = String::randString(16);
					$content = str_replace('{$user_name}', $user['first_name'] . ' '. $user['last_name'], $email_template['content']);
					$src = base64_encode($email.'###'.$token);
					$content = str_replace('{$url}', url('user/validate_email_callback', 'src='.$src), $content);
					$mailInstance = new EmailModel();
					$content = $mailInstance->replaceMail($content);
					$title = $mailInstance->replaceMail($email_template['title']);
					if($mailInstance->sendMail_direct($email, $title, $content)){
						//保存到数据库
						$user_db = D('users');
						$set = array(
							'token' => $token,
							'time' =>	time(),
						);
						$set = array_merge($set, $user['data']);
						$user_db->where(array('id' => $user['id']))->save(array('data' => serialize($set)));
						$this->success(L('_EMAIL_SENT_SUCCESSFULLY_'), url('user/user_safe'));
					}else{
						$this->error(L('_EMAIL_SENT_FAILURE_'), url('user/user_safe'));
					}
				}else{
					$this->error(L('_NOT_SUPPERT_'), url('user/user_safe'));
				}
	}
	
	//邮箱认证回调
	public function validate_email_callback()
	{
		global $user, $language_id;
		$this->checklogin();
		$src = $_REQUEST['src'];
		if(empty($src)){
			redirect(url('user/user_safe'),'', L('_ERROR_ACTION_'));
		}
			$src_data = base64_decode($src);
			$src_data = explode('###', base64_decode($src));
			$email = $src_data[0];
			$token = $src_data[1];
			dump($src_data) ;
			$userInfo = UserModel::get_user_info_by_other(array('email' => $email));
			if(!$userInfo){
				$this->error(L('_USER_NOT_EXIST_'), url('user/register'));
			}
			if($userInfo['data'] && isset($userInfo['data']['token'])){
				if($userInfo['data']['token'] != $token  && (time()-$userInfo['data']['time'])> 43200){
					$this->error(L('_VALIDATION_EXPIRED_'), url('user/user_safe'));
				}
			}else{
				$this->error(L('_ILLEGAL_OPERATION_'), url(''));
			}
			
			//用户data字段中的token和时间
			if($userInfo['data']){
				unset($userInfo['data']['token']);
				unset($userInfo['data']['time']);
			}
			
			$data = array(
				'is_validate_email' => 1,
				'data' => $userInfo['data'],
			);
			if(UserModel::update_user($userInfo['id'], $data)){
				$this->success(L('_EMAIL_VALIDATE_SUCCESS_'), url('user/center'));
			}else{
				$this->error(L('_EMAIL_VALIDATE_FAILED_'));
			}
	}
	
	//会员中心
	public function center()
	{	
		redirect(url('user/order_list'));
		global $user;
		
		$this->checklogin();
		
		$templatefile = THEMES_PATH.'user/user_index.phtml';
		$this->assign('templatefile', $templatefile);
		
		
		$where['user_id'] = $user['id'];
		
		$order_db = D('orders');
		$order_items_db = D('orders_items');
		
		$order_db->field('id,order_sn,pay_amount,order_status,start_time, delivery_first_name, delivery_last_name');
		$order_db->order('id DESC');
		$order_db->group('orders.id');
		$order_db->where($where);
		$order_db->limit(0, 10);
		$ordersList = $order_db->select();
		if($ordersList){
			foreach ($ordersList as &$order){
				$order_items_db->field('product_name,product_id,custom_type,product.is_sell');
				$order_items_db->join('product ON product.id = orders_items.product_id');
				$order_items_db->where(array('order_id' => $order['id']));
				$order['productList'] = $order_items_db->select();
			}
			unset($order);
		}
		
		$this->assign('ordersList', $ordersList);
		
		$this->display('usercenter');
	}
	
	//会员信息
	public function info()
	{
		global $user;
		$data = array(
			'docTitle' => L('meta_title_user_info'),
			'docKeywords' => L('meta_keywords'),
			'docDescription' => L('meta_description'),
		);
		$this->assign($data);
		//$this->checklogin();
	if(UserModel::logged()){
		$_SESSION['center_type'] = 7;
        
        		if($_POST['dosubmit']){
        			$post = $_POST;
        //			import('COM.Validate');
        //			$email = trim($post['email']);
        //			if(empty($email) || !Validate::email($email)){
        //				$this->error(L('_EMAIL_FORMAT_ERROR_'), url('user/info'));
        //			}
        //			if(UserModel::validate_email_only($email, $user['id'])){
        //				$this->error(L('_EMAIL_ALREADY_EXISTS_'), url('user/info'));
        //			}
        			if ( (isset($_FILES['up_user_photo']) && $_FILES['up_user_photo']['tmp_name'])){
        				$info = $this->upload('user');
        				if(is_array($info)) {// 上传成功 获取上传文件信息
        					if(isset($info['up_user_photo'])){
        						$post['user_photo'] = UPLOAD_PATH . $info['up_user_photo']['savename'];
        					}
        				}else{
        					$this->error($info);
        				}
        			}
        			
        			if(isset($post['data']['country_id']) && $post['data']['country_id']){
        				$area_info = SiteModel::get_region_info($post['data']['country_id']);
        	  		if($area_info){
        	  			$post['data']['country'] = $area_info['name'];
        	  		}
        			}
        			
        			$result = UserModel::update_user($user['id'], $post);
        			
        			if($result){
        				$this->success(L('_OPERATION_SUCCESS_'), url('user/info'));
        			}else{
        				$this->error(L('_OPERATION_FAIL_'), url('user/info'));
        			}
        		}else{
        			$countryList = SiteModel::get_country_list();
        			$countryName = '';
        			if($countryList){
        				foreach($countryList as $country){
        					if($user['data']['country_id'] == $country['id']){
        						$countryName = $country['name'];
        					}
        				}
        			}
        			$this->assign('countryName', $countryName);
        			$this->assign('countryList', $countryList);
        			$this->assign('user', $user);
        			$templatefile = THEMES_PATH.'user/user_info.phtml';
        			$this->assign('templatefile', $templatefile);	
        			$this->display('usercenter');
        		}
		}else{
			$templatefile = THEMES_PATH.'user/user_login.phtml';
			$this->assign('templatefile', $templatefile);	
			$this->display('usercenter');
		}
		
	}
	
	//会员中心修改密码
	public function user_password()
	{
		global $user;
		
		$this->checklogin();
		
		if($_POST['dosubmit']){
			
			$oldpassword = trim($_POST['oldpassword']);
			$userInfo = UserModel::get_user_info($user['id']);
			list($md5password, $rand_salt) = UserModel::generate_password($oldpassword, $userInfo['rand_salt']);
			if($userInfo['password'] != $md5password){
				$this->error(L('_THE_OLD_PASSWORD_ERROR_'), url('user/user_password'));
			}
			$password = $_POST['password'];
			import('COM.Validate');
			$validate = new Validate();
			if(empty($password) || !$validate->len($password,6,20)){
				$this->error(L('_THE_PASSWORD_SHOULD_BE_BETWEEN_6_20_'));
			}
			if(empty($_POST['confirm_password']) || $_POST['confirm_password'] != $password){
				$this->error(L('_ENTER_THE_PASSWORD_TWICE_INCONSISTENT_'));
			}
			$data = array(
				'password' => $password,
			);
			if(UserModel::update_user($userInfo['id'], $data)){
				$this->success(L('_PASSWORD_EDIT_SUCCESS_'), url('user/center'));
			}else{
				$this->error(L('_PASSWORD_EDIT_FAILED_'));
			}
		}else{
			$this->assign('user', $user);
			$templatefile = THEMES_PATH.'user/user_password.phtml';
			$this->assign('templatefile', $templatefile);
			$this->display('usercenter');
		}
	}
	
	//账户记录明细
	public function account_detail()
	{
		global $user;
		
		$this->checklogin();
		$where = array(
            'user_id' => $user['id'],
            'user_money' => array('neq', 0),
			);
		$user_account_db = D('user_account_log');
		$user_account_db->where($where);
		$count = $user_account_db->count();
		require THEMES_PATH.'page.php';
		$Page = new Page($count,20);
		$pageShow = $Page->show();
		$this->assign('pageShow', $pageShow);
		
		$user_account_db->where($where);
		$user_account_db->limit($Page->firstRow.','.$Page->listRows);
		$accountList = $user_account_db->order('id desc')->select();
		$this->assign('accountList', $accountList);
		
		$templatefile = THEMES_PATH.'user/account_detail.phtml';
		$this->assign('templatefile', $templatefile);
		$this->display('usercenter');
	}
	
	//充值
	public function account_recharge()
	{
		global $user;
		
		$this->checklogin();
		
		if($_POST['dosubmit']){
			if(empty($_POST['payment']) || !is_numeric($_POST['amount'])){
				$this->error(L('_OPERATION_FAIL_'), url('user/user_account'));
			}
			
			if(floatval($_POST['amount']) == '0.00'){
				$this->error(L('_OPERATION_FAIL_'), url('user/user_account'));
			}
			
			$data = array(
				'user_id' => $user['id'],
				'admin_user' => '',
				'is_paid' => 0,
				'amount' => floatval($_POST['amount']),
				'process_type' => 0,
				'admin_note' => '',
				'user_note' => trim($_POST['user_note']),
				'payment' => trim($_POST['payment']),
				'add_time' => time(),
				'paid_time' => time(),
			  );
			$user_db = D('user_account');
			$acc_id = $user_db->add($data);
			if($acc_id){
				$this->success(L('_OPERATION_SUCCESS_'), url('user/account_pay', array('payment' => $_POST['payment'], 'acc_id' => $acc_id)));
			}else{
				$this->error(L('_OPERATION_FAIL_'), url('user/user_account'));
			}
		}else{
			$paymentList = PaymentModel::get_payment_list();
			$this->assign('paymentList', $paymentList);
			$templatefile = THEMES_PATH.'user/account_recharge.phtml';
			$this->assign('templatefile', $templatefile);
			$this->display('usercenter');
		}
	}
	
	//提现
	public function account_deposit()
	{
		global $user;
		
		$this->checklogin();
		
		if($_POST['dosubmit']){
			if(floatval($_POST['amount']) == '0.00'){
				$this->error(L('_OPERATION_FAIL_'), url('user/user_account'));
			}
			$data = array(
				'user_id' => $user['id'],
				'admin_user' => '',
				'is_paid' => 0,
				'amount' => floatval($_POST['amount']),
				'process_type' => 1,
				'admin_note' => '',
				'user_note' => trim($_POST['user_note']),
				'payment' => '',
				'add_time' => time(),
				'paid_time' => time(),
			);
			$user_db = D('user_account');
			$acc_id = $user_db->add($data);
			if($acc_id){
				$this->success(L('_OPERATION_SUCCESS_'), url('user/user_account'));
			}else{
				$this->error(L('_OPERATION_FAIL_'), url('user/user_account'));
			}
		}else{
			$templatefile = THEMES_PATH.'user/account_deposit.phtml';
			$this->assign('templatefile', $templatefile);
			$this->display('usercenter');
		}
	}
	
	//取消资金操作
	public function account_cancel()
	{
		global $user;
		
		$this->checklogin();
		
		$account_id = intval($_GET['acc_id']);
		$user_account_db = D('user_account');
		$user_account_db->delete($account_id);
		$this->success(L('_OPERATION_SUCCESS_'), url('user/user_account'));
	}
	
	//资金管理
	public function user_account()
	{
		global $user;
		$data = array(
			'docTitle' => L('meta_title_user_account'),
			'docKeywords' => L('meta_keywords'),
			'docDescription' => L('meta_description'),
		);
		$this->assign($data);
		//$this->checklogin();
		if(UserModel::logged()){
		$_SESSION['center_type'] = 9;
		$user_account_db = D('user_account');
		$user_account_db->where('user_id='. $user['id']);
		$count = $user_account_db->count();
		require THEMES_PATH.'page.php';
		$Page = new Page($count,10);
		$pageShow = $Page->show();
		$this->assign('pageShow', $pageShow);
		
		$user_account_db->where('user_id='. $user['id']);
		$user_account_db->limit($Page->firstRow.','.$Page->listRows);
		$accountList = $user_account_db->order('id desc')->select();
		$this->assign('accountList', $accountList);
		
		$templatefile = THEMES_PATH.'user/user_account.phtml';
		$this->assign('templatefile', $templatefile);
		}else{
		$templatefile = THEMES_PATH.'user/user_login.phtml';
		$this->assign('templatefile', $templatefile);			
		}
		$this->display('usercenter');
	}
	
	//会员充值付款
	public function account_pay()
	{
		
		$this->checklogin();
		
		$payment_name = trim($_GET['payment']);
		$account_id = intval($_GET['acc_id']);
		$user_account_db = D('user_account');
		$user_account_db->field('id,amount,payment');
		$accountInfo = $user_account_db->where('user_account.id='.$account_id)->find();
		$payment_name = $accountInfo['payment'];
		$paymentInfo = PaymentModel::get_payment_info($payment_name);
		$accountInfo['payment_fee'] = PaymentModel::get_paymeent_fee($payment_name, $accountInfo['amount']);
		$accountInfo['pay_amount'] = $accountInfo['amount'] + $accountInfo['payment_fee'];
		$accountInfo['order_sn'] = 'recharge_'.$account_id;
		
		//支付按钮
		import('COM.Payment');
		$paymentInstance = Payment::getInstance($payment_name);
		$paymentSubmit = $paymentInstance->getSubmitForm($accountInfo);
		$this->assign('paymentSubmit', $paymentSubmit);
		
		$templatefile = THEMES_PATH.'user/account_pay.phtml';
		$this->assign('templatefile', $templatefile);
		$this->assign('account', $accountInfo);
		$this->assign('paymentInfo', $paymentInfo);
		$this->display('usercenter');
	}
	
	//订单列表
	public function order_list()
	{
		global $user;
		$data = array(
    		'docTitle' => L('meta_title_order_list'),
    		'docKeywords' => L('meta_keywords'),
    		'docDescription' => L('meta_description'),
    	);
		$this->assign($data);		
		//$this->checklogin();
		if(UserModel::logged()){
		if($_GET['order_status']==-1){
			$_SESSION['center_type'] = 2;
		}else{
			$_SESSION['center_type'] = 1;
		}
		
		
		$post = array_merge($_GET,$_POST);
        $where['orders.order_status'] = array('neq','-2'); 
		$where['orders.user_id'] = $user['id'];
		if($post['order_status'] != ''){
			$order_status = intval($post['order_status']);
			if($order_status == 100) 
				$order_status = 0;
			$where['order_status'] = $order_status;
		}
		if($post['payment_status'] != ''){
			$payment_status = intval($post['payment_status']);
			if($payment_status == 100) 
				$payment_status = 0;
			$where['payment_status'] = $payment_status;
		}
		if($post['shipping_status'] != ''){
			$where['shipping_status'] = intval($post['shipping_status']);
		}
		if($post['order_sn'] != ''){
			$order_sn = trim($post['order_sn']);
			$sqlstr = "(order_sn like '%".$order_sn."%' ";
			$sqlstr .= " or concat(delivery_first_name,delivery_last_name) like '%".str_replace(" ","",$order_sn)."%')";
			$where['_string'] = $sqlstr;
			$this->assign('order_sn', $order_sn);
		}
		if($post['start_time']){
			$where['start_time'] = array('gt', strtotime($post['start_time']));
		}
		if($post['end_time']){
			$where['start_time'] = array('lt', strtotime($post['end_time']));
		}
		$order_db = D('orders');
		$order_item_db = D('orders_items');
		
		//分页
		$order_db->where($where);
		$count = $order_db->count();//总记录数
		require THEMES_PATH.'page.php';// 导入分页类
		$Page = new Page($count,15);// 实例化分页类 传入总记录数和每页显示的记录数
		$pageShow = $Page->show();// 分页显示输出
		$this->assign('pageShow', $pageShow);
		
		$order_db->field('orders.id,order_sn,order_amount,
			pay_amount,order_status,payment_status,shipping_status,
			start_time, comment.id as is_comment, payment_method,
			delivery_first_name,delivery_last_name,delivery_email,
			delivery_phone,delivery_mobile,delivery_cid,delivery_pid,
            delivery_country,delivery_province,delivery_city,delivery_address,
            delivery_address2,delivery_address3,delivery_postcode,delivery_time,
            delivery2_first_name,delivery2_last_name,delivery2_email,delivery2_phone,
            delivery2_cid,delivery2_country,delivery2_province,delivery2_city,
            delivery2_address,delivery2_address2,delivery2_address3,delivery2_postcode');
		$order_db->order('orders.id DESC');
		$order_db->limit($Page->firstRow.','.$Page->listRows);
		$order_db->join('`comment` ON comment.order_id = orders.id');
		$order_db->group('orders.id');
		$order_db->where($where);
		$ordersList = $order_db->select();
		//var_dump($ordersList);
		if($ordersList){
			foreach ($ordersList as &$row){
				
				$order_item_db->field('product.yushou_end_time,product.weikuan_time,product.product_type,car_type');
				$order_item_db->join('product ON product.id = orders_items.product_id');
				$order_item_db->where(array('order_id' => $row['id']));
				$productInfo = $order_item_db->find();
				if($productInfo){
					$row['yushou_end_time'] 	= $productInfo['yushou_end_time'];
					$row['weikuan_time'] 		= $productInfo['weikuan_time'];
					$row['product_type'] 		= $productInfo['product_type'];
					$row['car_type'] 			= $productInfo['car_type'];
				}
				$pay_return_db = D('orders_pay_return');
				$returnInfo = $pay_return_db->where('order_sn="'.$row['order_sn'].'" AND car_type=1')->find();
				//判断是否已申请退款
				if($returnInfo){
					$row['pay_return'] = 1;
					if($returnInfo['status']==2)
						$row['return_status'] = L('refunded');//已退款
					else
						$row['return_status'] = L('a_refund_of');//退款中
				}else{
					$row['pay_return'] = 0;
				}
                
				//支付按钮
				if(!in_array($row['order_status'], array(OrderModel::ORDER_CANCELED, OrderModel::ORDER_DEL))
					    && $row['payment_status'] == OrderModel::PAY_UNPAYED ){
					//有产品下架的情况下不让支付
					if(!orderModel::get_order_product_isdown($row['id'])){
	                    $paymentSubmit  = '';
	                    $paymentSubmit .= '<form id="frm" method="post" action="'.url('cart/ordersuccee',array('oid'=>$row['id'])).'" target="_blank">';
						$paymentSubmit .= '<input class="pay_button" type="submit" value="'.L('_PAY_NOW_').'">';
						$paymentSubmit .= '</form>';
						$row['paymentSubmit'] = $paymentSubmit;
				    }
				}
				if($row['order_status'] == OrderModel::ORDER_COMPLETE){
                   $orders_items = D('orders_items')->field('id')->where(array('order_id'=>$row['id']))->select();
                   $row['add_comment'] = false;
				   foreach ($orders_items as $orders_items_id) {
				        //是否评论过
				        $comment_where = array(
				        	'order_items_id'=>$orders_items_id['id'],
				        );
				        $comment_res = M('comment')->where($comment_where)->count();
				        if(!$comment_res){
				        	$row['add_comment'] = true;break;
				        }
				   }
				}
			}
			unset($row);
		}
		$this->assign('ordersList', $ordersList);
		
		$templatefile = THEMES_PATH.'user/order_list.phtml';
		$this->assign('templatefile', $templatefile);
		//$osid = $_GET['order_status'];
		$order_result['osid'] = $post['order_status'];
		if($post['order_status'] >=0 && $post['order_status'] != NULL){
			$order_result['name'] = L(OrderModel::$orderStatus[$order_status]);
		}else{
			$order_result['name'] = L('any');
		}
		$payment_result['psid'] = $post['payment_status'];
		if($post['payment_status']>=0 && $post['payment_status'] != NULL){
			$payment_result['name'] = L(OrderModel::$paymentStatus[$payment_status]);
		}else{
			$payment_result['name'] = L('any');
		}
		//判断session是否存在，不存在查询商品总数量
		if(!isset($_SESSION['cart']['number'])){
			$cart_products_db = D('cart_products');
			$cartProductsInfo = $cart_products_db->where(array('user_id'=>$user['id']))->sum('qty');
			$_SESSION['cart']['number']=$cartProductsInfo;
		}
		$this->assign('order_result', $order_result);
		$this->assign('payment_result', $payment_result);
		}else{
			$templatefile = THEMES_PATH.'user/user_login.phtml';
			$this->assign('templatefile', $templatefile);
		}
		$this->display('usercenter');
	}
	//会员取消订单
	public function order_cancel(){
		global $language_id,$user;
		$this->checklogin();
		$order_id = intval($_GET['oid']);
		$orderInfo = OrderModel::get_order_info($order_id);
        //过滤不合法的请求
        if($orderInfo['user_id'] != $user['id']){
            $this->error(L('_ERROR_ACTION_'), url('user/order_list')); 
            exit;
        }
        //var_dump($orderInfo);die;
        //只有订单是未确认，未支付状态 才能取消操作
        $post = array();
        if( ($orderInfo['order_status'] == OrderModel::ORDER_UNCONFIRMED) && ($orderInfo['payment_status'] == OrderModel::PAY_UNPAYED) ){
  			$post = array(
                'order_status' => OrderModel::ORDER_CANCELED,
  		    );
  		    $res = OrderModel::update_order_status($order_id, $post);
  		    if($res){
  		    	//如果订单有使用红包，则返回用户红包
  		    	$user_bonus_where = array(
  		    		'bonus_sn' => $orderInfo['order_sn'],
  		    		'used_time'  => array('gt',0),
  		    	);
                D('user_bonus')->where($user_bonus_where)->save(array('bonus_sn'=>0,'used_time'=>0));
                //释放优惠码
                $coupon_info = M('favorable')->where("coupon_code = '".$orderInfo['coupon_code']."'")->find();
                if($coupon_info['status'] == 0 || $coupon_info['count']){
                    if($coupon_info['type'] == 4 || $coupon_info['type'] == 2){//类型为2和4的是有使用限制的优惠码
                        $fdata['status'] = $coupon_info['type']; //
                        $fdata['usage_count'] = $coupon_info['usage_count'] + 1;//优惠码可使用次数+1
                    }else{
                            $fdata['status'] = 2;
                    }
                    $fdata['id'] = $coupon_info['id'];
                    M('favorable')->save($fdata);
                }
                //返回余额
                $surplus_money = floatval($orderInfo['surplus_money']);
                if($orderInfo['user_id'] > 0 && $surplus_money > 0){
                    //订单取消返回相应余额到账户
                    $tips = L('cancel_order').' '.$orderInfo['order_sn'];
				    UserModel::user_account_change($orderInfo['user_id'], $surplus_money, 0, 1, NULL, $tips, NULL);
				    UserModel::log_account_change($orderInfo['user_id'], $surplus_money, 0, 0 ,0, $tips, UserModel::ACT_SAVING);
                }
                
                //取消的原因
				$logData = array(
			  		'order_id' => $order_id,
				  	'order_status' => OrderModel::ORDER_CANCELED,
				  	'payment_status' => $orderInfo['payment_status'],
				  	'shipping_status' => $orderInfo['shipping_status'],
			  		'action_notice' => $this->_request('message') ? trim($this->_request('message')) : null,
			  		'action_name' => $user['email'],
			  		'pro_type' => 1,
				);
            	if(intval($this->_request('canceltype'))>0)
            	    $logData['type']     = $this->_request('canceltype');					

				OrderModel::insert_orders_log($logData);
                
                //发送取消订单邮件
				$mailInstance = new EmailModel();
				$email_template = UserModel::get_email_template_info('orderCancelEmail', $orderInfo['language_id']);
				if($email_template){
					$content = $mailInstance->replaceMail($email_template['content'], $orderInfo);
					$title = $mailInstance->replaceMail($email_template['title']);
					$mailInstance->sendMail($orderInfo['delivery_email'], $title, $content);
				}
				                
                //成功提示
                $this->success(L('order_canceled_ok'), url('user/order_list')); 
                exit;
  		    }   	
        }
        $this->error(L('operation_failed'), url('user/order_list'));  		        
	}
	//会员中心订单详细页
	public function order_info()
	{
		global $language_id,$user;
		$this->checklogin();
		
		$order_id = intval($_GET['oid']);
		$orderInfo = OrderModel::get_order_info($order_id);
		
        //过滤不合法的请求
        if($orderInfo['user_id'] != $user['id']){
            $this->error(L('_ERROR_ACTION_'), url('user/order_list')); 
            exit;
        }
		$pay_return_db = D('orders_pay_return');
		$returnInfo = $pay_return_db->where('order_sn="'.$orderInfo['order_sn'].'" AND car_type=1')->find();
		//判断是否已申请退款
		if($returnInfo){
			$orderInfo['pay_return'] = 1;
			
			if($returnInfo['status']==2)
				$orderInfo['return_status'] = L('refunded');
			else
				$orderInfo['return_status'] = L('a_refund_of');
		}else{
			$orderInfo['pay_return'] = 0;
		}
		$order_item_db = D('orders_items');
		$order_item_db->field('product.yushou_end_time,product.weikuan_time,product.product_type,car_type');
		$order_item_db->join('product ON product.id = orders_items.product_id');
		$order_item_db->where(array('order_id' => $order_id));
		$productInfo = $order_item_db->find();
		$orderInfo['car_type'] = $productInfo['car_type'];
		$this->assign('yushou_end_time', $productInfo['yushou_end_time']);
		$this->assign('weikuan_time', $productInfo['weikuan_time']);
			
		if(!$orderInfo){
			$this->error(L('_ORDER_NO_EXIST_'), url('user/order_list'));
		}
		$orderInfo['payment'] = PaymentModel::get_payment_info($orderInfo['payment_method']);
		//看用户可以使用多少积分支付
		$total_amount = $orderInfo['product_amount']+$orderInfo['payment_fee']+$orderInfo['shipping_fee'];
		$use_integral = UserModel::get_user_integral($total_amount);
		if(is_array($use_integral))
			list($total_integral, $integral_money) = $use_integral;
		$this->assign('total_integral', isset($total_integral) ? $total_integral : 0);
		$this->assign('integral_money', isset($integral_money) ? $integral_money : 0);
			
		//看用户可以使用多少红包
		$bonusList = UserModel::get_bonus_list();
		if($bonusList)
			$this->assign('bonusList', $bonusList);
		 //订单产品列表
		$orderInfo['productList'] = OrderModel::get_order_product_list($order_id);
		//读取购物车中定制商品的定制信息
		foreach ($orderInfo['productList'] as $key => $order_items) {
			$attr = $order_items['original_attr'];
			if($order_items['custom_type'] == '2' && is_array($attr)){	
	            list($attributeList, $size_type) = CartModel::cart_attr_show($order_items['product_id'], serialize($attr));
			    $orderInfo['productList'][$key]['attributeList'] = $attributeList;
			    $orderInfo['productList'][$key]['size_type']     = $size_type;
		    }
		}
		// echo "<pre />";
		// print_r($orderInfo['productList']);exit;		
		//发货单列表
		$orderInfo['deliveryList'] = OrderModel::get_delivery_list($order_id);
		//查询订单中是否有商品已经下架
		$order_down_product = orderModel::get_order_product_isdown($order_id);
		$this->assign('order_down_product', $order_down_product);
		//支付按钮
		// if(!in_array($orderInfo['order_status'], array(OrderModel::ORDER_CANCELED, OrderModel::ORDER_DEL))
		// 	&& $orderInfo['payment_status'] == OrderModel::PAY_UNPAYED){
		// 	//有产品下架的情况下不让支付
		// 	if(!$order_down_product){
		// 		import('COM.Payment');
		// 		$paymentInstance = Payment::getInstance($orderInfo['payment_method']);
		// 		$payOrderInfo = $orderInfo;
		// 		$payOrderInfo['currency'] = isset($_SESSION['currency']) && $_SESSION['currency'] ? $_SESSION['currency'] : C('currency'); //币种
		// 		$payOrderInfo['pay_amount'] = currency($orderInfo['pay_amount'],null,false);
		// 		$paymentSubmit = $paymentInstance->getSubmitForm($payOrderInfo);
		// 		$this->assign('paymentSubmit', $paymentSubmit);
		//     }
		// }
        //var_dump($paymentSubmit);die;
		$this->assign('orderInfo', $orderInfo);
		$user_money = M('users')->field('user_money')->where('id='.$user['id'])->find();
        $this->assign('user_money',$user_money['user_money']);
		$paymentList = PaymentModel::get_payment_list();
		$this->assign('paymentList', $paymentList);
		$shippingList = ShippingModel::get_shipping_list();
		$this->assign('shippingList', $shippingList);
		$countryList = SiteModel::get_country_list();
		$this->assign('countryList', $countryList);
		
		/*if($productInfo['car_type'] > 0)
			$templatefile = THEMES_PATH.'user/order_info02.phtml';
		else*/
		$templatefile = THEMES_PATH.'user/order_info.phtml';
		$this->assign('templatefile', $templatefile);
		$this->display('usercenter');
	}
	
	public function account_point()
	{
		global $user;
		$data = array(
			'docTitle' => L('meta_title_account_point'),
			'docKeywords' => L('meta_keywords'),
			'docDescription' => L('meta_description'),
		);
		$this->assign($data);		
		//$this->checklogin();
		if(UserModel::logged()){
		$_SESSION['center_type'] = 11;
		$where = array(
			'user_id' => $user['id'],
			//'rank_points' => array('neq', 0),
			'pay_points' => array('neq', 0),
		);
		
		$user_account_db = D('user_account_log');
		$user_account_db->where($where);
		$count = $user_account_db->count();
		require THEMES_PATH.'page.php';
		$Page = new Page($count,20);
		$pageShow = $Page->show();
		$this->assign('pageShow', $pageShow);
		
		$user_account_db->where($where);
		$user_account_db->limit($Page->firstRow.','.$Page->listRows);
		$accountList = $user_account_db->order('id desc')->select();
		//echo $user_account_db->getLastSql();
		$this->assign('accountList', $accountList);
		
		$templatefile = THEMES_PATH.'user/account_point.phtml';
		$this->assign('templatefile', $templatefile);
		}else{
		$templatefile = THEMES_PATH.'user/user_login.phtml';
		$this->assign('templatefile', $templatefile);			
		}
		$this->display('usercenter');
	}

	
	//配送地址列表
	public function address_list()
	{
		global $user;
		$data = array(
			'docTitle' => L('meta_title_address_list'),
			'docKeywords' => L('meta_keywords'),
			'docDescription' => L('meta_description'),
		);
		$this->assign($data);		
		//$this->checklogin();
		if(UserModel::logged()){
		$_SESSION['center_type'] = 13;
		$aid = intval($_GET['aid']);
		
		if($_POST['dosubmit']){
				if(UserModel::update_user_address($user['id'], $_POST)){
				$this->success(L('_OPERATION_SUCCESS_'), url('user/address_list'));
			}else{
				$this->error(L('_OPERATION_FAIL_'));
			}
		}else{
			if($aid){
				$address_db = D('user_address');
				$addressInfo = $address_db->find($aid);
			}
			$this->assign('addressInfo', isset($addressInfo) ? $addressInfo : array() );
			$countryList = SiteModel::get_country_list();
			$this->assign('countryList', $countryList);
			
		$addressList = UserModel::get_address_list($user['id']);
		$this->assign('addressList', $addressList);
		
		$templatefile = THEMES_PATH.'user/address_list.phtml';
		$this->assign('templatefile', $templatefile);

		}
		}else{
		$templatefile = THEMES_PATH.'user/user_login.phtml';
		$this->assign('templatefile', $templatefile);			
		}
		$this->display('usercenter');
	}
	
	//添加编辑配送地址
	public function address_edit()
	{
		global $user;
		
		$this->checklogin();
		
		$aid = intval($_GET['aid']);
		
		if($_POST['dosubmit']){
				if(UserModel::update_user_address($user['id'], $_POST)){
				$this->success(L('_OPERATION_SUCCESS_'), url('user/address_list'));
			}else{
				$this->error(L('_OPERATION_FAIL_'));
			}
		}else{
			$address = array();
			if($aid){
				$address_db = D('user_address');
				$address = $address_db->find($aid);
			}
			$this->assign('address', $address);
			$countryList = SiteModel::get_country_list();
			$this->assign('countryList', $countryList);
//			$this->display('address_form');
			$templatefile = THEMES_PATH.'user/address_info.phtml';
			$this->assign('templatefile', $templatefile);
			$this->display('usercenter');
		}
	}
	//删除配送地址
	public function address_delete()
	{
		global $user;
		
		$this->checklogin();
		$is_ajax = (boolean)($_GET['is_ajax']);
		$aid = intval($_GET['aid']);
		$address_db = D('user_address');
		$address = $address_db->find($aid);
		$address_db->delete($aid);
		$message = L('_OPERATION_SUCCESS_');
		if($is_ajax){
			return $message;exit;
		}else{
			$this->success($message, url('user/address_list'));
		}
	}
	
	//会员评论
	Public function comment_list()
	{
		global $user;
		$data = array(
			'docTitle' => L('meta_title_comment_list'),
			'docKeywords' => L('meta_keywords'),
			'docDescription' => L('meta_description'),
		);
		$this->assign($data);		
		$this->checklogin();
		$_SESSION['center_type'] = 14;
		$comment_db = D('comment');
		
		//分页
		$where['user_id'] = $user['id'];
		$comment_db->where($where);
		$count = $comment_db->count();//总记录数
		require THEMES_PATH.'page.php';// 导入分页类
		$Page = new Page($count,20);// 实例化分页类 传入总记录数和每页显示的记录数
		$pageShow = $Page->show();// 分页显示输出
		$this->assign('pageShow', $pageShow);
		
		$comment_db->order('id DESC');
		$comment_db->limit($Page->firstRow.','.$Page->listRows);
		$comment_db->where($where);
		$commentList = $comment_db->select();
		if($commentList){
			foreach ($commentList as &$com){
				if($com['product_id'])
					$com['product'] = ProductModel::get_product_info($com['product_id']);
			}
		}
		$this->assign('commentList', $commentList);

		
		$templatefile = THEMES_PATH.'user/comment_list.phtml';
			$this->assign('templatefile', $templatefile);
			$this->display('usercenter');
	}
	
	public function comment_add()
	{
		global $user;
		
		$this->checklogin();
		
		$order_id = intval($_GET['oid']);
		$orderInfo = OrderModel::get_order_info($order_id);
		if(!$orderInfo || $orderInfo['user_id'] != $user['id']){
			$this->error(L('_ORDER_NO_EXIST_'), url('user/order_list'));
		}
		
		//提交
		if(isset($_POST['dosubmit']))
		{
			if($_POST['comment_token'] != $_SESSION['comment_token'])
			{
				$this->error(L('_OPERATION_FAIL_'), url('user/comment_add', 'oid='.$order_id));
			}
			$post = $_POST['comment'];
			foreach ($post as $comment){
				if(empty($comment['content'])){
					continue;
				}
				$comment['order_id'] = $order_id;
				$comment['username'] = $user['username'];
				$comment['email'] = $user['email'];
				$result = CommentModel::insert_comment($comment);
			}
			
			if(empty($post)){
				$this->error(L('_OPERATION_FAIL_'), url('user/order_list'));
			}elseif(isset($result) && $result){
				$this->success(L('_OPERATION_SUCCESS_'), url('user/order_list'));
			}else{
				$this->error(L('_OPERATION_FAIL_'), url('user/comment_add', 'oid='.$order_id));
			}
		}else{
     if(!isset($_SESSION['comment_token']) || empty($_SESSION['comment_token'])){
	     import('ORG.Util.String');
	     $_SESSION['comment_token'] = String::randString(16);
     }
     $this->assign('comment_token',  $_SESSION['comment_token']);
     
     $orderInfo['productList'] = OrderModel::get_order_product_list($order_id);
  //    echo "<pre />";
		// print_r($orderInfo);exit;
			$this->assign('orderInfo', $orderInfo);
			$templatefile = THEMES_PATH.'user/comment_add.phtml';
			$this->assign('templatefile', $templatefile);
			$this->display('usercenter');
		}
	}

	public function comment_add_ajax()
	{
		global $user;
		$this->checklogin();
		$post = $_POST;

		$error = 1;
		$errStr = '';
        //是否有这个订单数据
        $orders_items_where = array(
        	'id'=>$post['oitemsid'],
        );
        $order_items = M('orders_items')->field('id,order_id,product_id')->where($orders_items_where)->find();
        //验证
		$order_id = ($order_items && $order_items['order_id'] > 0 ? $order_items['order_id'] : 0);
		$orderInfo = OrderModel::get_order_info($order_id);
		if(!$orderInfo || $orderInfo['user_id'] != $user['id']){
	        $info = array(
	        	'error' => 0,
	        	'errStr' => L('_OPERATION_FAIL_'), 
	        );
			echo json_encode($info);exit;
		}

        //是否评论过
        $comment_where = array(
        	'order_items_id'=>$order_items['id'],
        	'product_id'=>$order_items['product_id'],
        );
        $comment_res = M('comment')->where($comment_where)->count();
        //不能评论
		if(!$order_items || $comment_res || empty($post['content'])){
	        $info = array(
	        	'error' => 0,
	        	'errStr' => L('_OPERATION_FAIL_'), 
	        );
			echo json_encode($info);exit;	
		}
		$comment = array(
                'star'       => $post['star'],
                'content'    => $post['content'],
                'order_id'   => $order_items['order_id'],
				'product_id' => $order_items['product_id'],
				'order_items_id'   => $order_items['id'],				
				'user_id'    => $user['id'],
				'username'   => $user['username'],
				'email'      => $user['email'],
			);
		$result = CommentModel::insert_comment($comment);
		
        if(isset($result) && $result){
        	//绑定图片
        	$comment_photo_db = D('comment_photo');
            $comdata = array('comid'=>$result);
    		$addimg = $post['addimg'];
			if($addimg){
				$addimg = explode(',', $addimg);
				foreach ($addimg as $key => $val) {
					if(intval($val)){
                        $comment_photo_db->where(array('fid'=>$val)) ->save($comdata);
					}
				}
			}
            //删除图片
    		$delimg = $post['delimg'];
			if($delimg){
				$delimg = explode(',', $delimg);
				foreach ($delimg as $key => $val) {
					if(intval($val)){
                        $comment_photo_db->where(array('fid'=>$val,'user_id'=>$user['id'])) ->delete();
					}
				}
			} 			           	
			$info = array(
	        	'error' => 1, 
	        	'errStr' => L('_OPERATION_SUCCESS_'), 
	        );
		}else{
	        $info = array(
	        	'error' => 0, 
	        	'errStr' => L('_OPERATION_FAIL_'), 
	        );
		}
		echo json_encode($info);exit;
	}
	
	public function guestbook_list()
	{
		global $user;
		
		$this->checklogin();
		$guestbook_db = D('guestbook');
		$product_photo_db = D('product_photo');
		
		$type = intval($_GET['type']);
		if($type == 1){
			$_SESSION['center_type'] = 16;
		}else{
			$_SESSION['center_type'] = 5;
		}
		
		/*if($type ==0){
			$where['message_type'] = 4;
		}else{
			$zixunType = CommentModel::$zixunType;
			$where['message_type'] = array('in', array_keys($zixunType));
		}*/
		if($_REQUEST['message_type']==1)
			$type = 1;
			
		if($type > 0){
			$where['message_type'] = 1;
		}else{
			$where['message_type'] = 2;
		}
		
		//分页
		$where['user_id'] = $user['id'];
		$guestbook_db->where($where);
		$count = $guestbook_db->count();//总记录数
		require THEMES_PATH.'page.php';// 导入分页类
		$Page = new Page($count,20);// 实例化分页类 传入总记录数和每页显示的记录数
		$pageShow = $Page->show();// 分页显示输出
		$this->assign('pageShow', $pageShow);
		
//		$guestbook_db->field('id,message_type,title,content,start_time,reply,reply_time');
		$guestbook_db->order('start_time DESC');
		$guestbook_db->limit($Page->firstRow.','.$Page->listRows);
		$guestbook_db->where($where);
		$guestbookList = $guestbook_db->select();
		//echo $guestbook_db->getLastSql();
		if($guestbookList){
			foreach ($guestbookList as &$gb){
				if($gb['data']){
					$data = unserialize($gb['data']);
					if($data['images']){
						$gb['photoList'] = $product_photo_db->field('img')->where(array('fid' => array('in', $data['images'])))->select();
					}
				}
			}
			unset($gb);
		}
		
		$this->assign('guestbookList', $guestbookList);
		
		if(!isset($_SESSION['comment_token']) || empty($_SESSION['comment_token'])){
	     import('ORG.Util.String');
	     $_SESSION['comment_token'] = String::randString(16);
     }
     $this->assign('comment_token',  $_SESSION['comment_token']);
		
    if($type){
			$templatefile = THEMES_PATH.'user/guestbook_zixun.phtml';
    }else{
    	$templatefile = THEMES_PATH.'user/guestbook_list.phtml';
    }
		$this->assign('templatefile', $templatefile);
		$this->display('usercenter');
	}
	
	public function guestbook_add()
	{
		global $user;
		
		$this->checklogin();
		
		//提交
		if(isset($_POST['dosubmit']))
		{
			$post = $_POST;
			$message_type = intval($post['message_type']);

			if($_POST['comment_token'] != $_SESSION['comment_token'])
			{
				$this->error(L('_OPERATION_FAIL_'), url('user/guestbook_list', array('message_type' => $message_type)));
			}
				if(empty($post['title']) && empty($post['content'])){
					$this->error(L('_OPERATION_FAIL_'), url('user/guestbook_list', array('message_type' => $message_type)));
				}
				$data = array(
					'message_type' => $message_type,
					'title' => trim($post['title']),
					'content' => trim($post['content']),
					'user_id' => $user['id'],
					'language_id' => $user['language_id'],
					'username' => $user['[first_name'],
					'email' => $user['email'],
					'data' => $post['data'],
				);
				
				$gbid = CommentModel::insert_guestbook($data);
			
			if($gbid){
				$this->success(L('_OPERATION_SUCCESS_'), url('user/guestbook_list', array('message_type' => $message_type)));
			}else{
				$this->error(L('_OPERATION_FAIL_'), url('user/guestbook_list', array('message_type' => $message_type)));
			}
		}else{
     if(!isset($_SESSION['comment_token']) || empty($_SESSION['comment_token'])){
	     import('ORG.Util.String');
	     $_SESSION['comment_token'] = String::randString(16);
     }
     $this->assign('comment_token',  $_SESSION['comment_token']);
		
			//$templatefile = THEMES_PATH.'user/guestbook_add.phtml';
			$this->assign('templatefile', $templatefile);
			$this->display('usercenter');
		}
	}
	
	/**
	 * 添加收藏
	 */
	public function add_collect()
	{
		global $user;
		$result = array(
			'error' => 1,
			'message' => null,
		);
		if(! UserModel::logged()){
			$result['message'] = L('_LOGIN_BEFORE_COLLECTION_');
			$result['error'] = '-1';
		}else{
			$pid = intval($_REQUEST['pid']);
			$productInfo = ProductModel::get_product_info($pid);
			if(! $productInfo){
				$result['message'] =  L('_PRODUCT_NO_EXIST_');
			}else{
				$collect_db = D('user_collect');
				$count = $collect_db->where(array('user_id' => $user['id'], 'pid' =>$pid))->count();
				if(! $count){
					$data = array(
						'user_id' => $user['id'],
						'pid' => $pid,
						'add_time' => time(),
					);
					$collect_db->add($data);
				}
				$result['message'] = L('_HAVE_BEEN_COLLECTION_');
				$result['error'] = '0';
			}
		}
		echo json_encode($result);
	}
	
	//收藏列表
	public function collect_list()
	{
		global $user;
		$data = array(
			'docTitle' => L('meta_title_collect_list'),
			'docKeywords' => L('meta_keywords'),
			'docDescription' => L('meta_description'),
		);
		$this->assign($data);
		//$this->checklogin();
		if(UserModel::logged()){
		$_SESSION['center_type'] = 3;
		
		$collect_db = D('user_collect');
		$collectList = array();
		//分页
		$where['user_id'] = $user['id'];
		$collect_db->where($where);
		$count = $collect_db->count();
		
		if($count){
			require THEMES_PATH.'page.php';
			$Page = new Page($count,20);
			$pageShow = $Page->show();
			$this->assign('pageShow', $pageShow);
			
			$collect_db->order('add_time DESC');
			$collect_db->limit($Page->firstRow.','.$Page->listRows);
			$collect_db->where($where);
			$collectList = $collect_db->select();
			foreach ($collectList as $key => &$collect ){
				$productInfo = ProductModel::get_product_info($collect['pid']);
				if($productInfo){
				$collect['product'] = $productInfo;
				}else{
					unset($collectList[$key]);
				}
			}	
		}

		$this->assign('collectList', $collectList);		
		$templatefile = THEMES_PATH.'user/user_collect.phtml';
			$this->assign('templatefile', $templatefile);
		}else{
			$templatefile = THEMES_PATH.'user/user_login.phtml';
			$this->assign('templatefile', $templatefile);
		}
			$this->display('usercenter');
	}
	
	//删除收藏
	public function delete_collect()
	{
		global $user;
		$this->checklogin();
		$collect_id = intval($_GET['id']);
		$collect_ids = isset($_POST['ids']) ? $_POST['ids'] : '';
		if($collect_ids){
			$collect_id = join(',', $collect_ids);
		}
		echo $collect_id;exit;
		$collect_db = D('user_collect');
		$collect_db->delete($collect_id);
		$this->success(L('_OPERATION_SUCCESS_'), U('user/collect_list'));
	}
	
	//要退换订单中产品列表
	public function order_purchase_product_list()
	{
		global $user;
		$data = array(
			'docTitle' => L('meta_title_infoorder_product_list'),
			'docKeywords' => L('meta_keywords'),
			'docDescription' => L('meta_description'),
		);
		$this->assign($data);
		//$this->checklogin();
		if(UserModel::logged()){
		$_SESSION['center_type'] = 4;
		$where = array(
			'orders.order_status' => OrderModel::ORDER_CONFIRMED,
			'orders.payment_status' => array('in', array(OrderModel::PAY_PAYED, OrderModel::PAY_PARTIAL_REFUND)),
			'orders.shipping_status' => array('in', array(OrderModel::SHIPPING_SHIPPED,OrderModel::SHIPPING_SHIPPED_PART, OrderModel::SHIPPING_RECEIVED)),
			'orders.user_id' => $user['id'],
			'orders.end_time' => array(array('eq',0),array('gt', strtotime(date('Y-m-d', strtotime("-1 week").' 23:59:59'))), 'OR'),
		);
		$order_db = D('orders');
		//分页
		$order_db->where($where);
		$count = $order_db->count();//总记录数
		require THEMES_PATH.'page.php';// 导入分页类
		$Page = new Page($count,20);// 实例化分页类 传入总记录数和每页显示的记录数
		$pageShow = $Page->show();// 分页显示输出
		$this->assign('pageShow', $pageShow);
		
		$order_db->field('orders.id,order_sn,orders.start_time');
		$order_db->order('orders.id DESC');
		$order_db->limit($Page->firstRow.','.$Page->listRows);
		$order_db->where($where);
		$ordersList = $order_db->select();
		//echo $order_db->getLastSql();exit;
		$order_items_db = D('orders_items');
		if($ordersList){
			foreach ($ordersList as &$order){
				$order_items_db->field('orders_items.id AS orders_items_id,qty,orders_items.product_name,orders_items.pay_price,orders_items.product_id,product.small_img,op.status AS purchase_status,op.id AS purchase_id');
				$order_items_db->where(array('orders_items.order_id' => $order['id']));
				$order_items_db->join('product ON product.id = orders_items.product_id');
				$order_items_db->join('orders_purchase AS op ON op.orders_items_id = orders_items.id');
				$order['productList'] = $order_items_db->select();
//				echo $order_items_db->getLastSql();exit;
			}
		}

		$this->assign('ordersList', $ordersList);
		
		$templatefile = THEMES_PATH.'user/order_purchase_product_list.phtml';
		$this->assign('templatefile', $templatefile);
		}else{
			$templatefile = THEMES_PATH.'user/user_login.phtml';
			$this->assign('templatefile', $templatefile);	
		}
		$this->display('usercenter');
	}
	
	//退换货申请
	public function order_purchase_add()
	{
		global $user;
		$this->checklogin();
		
		$oiid = intval($_GET['oiid']);
		$order_items_db = D('orders_items oi');
		$order_items_db->field('delivery_first_name,delivery_last_name,delivery_phone,delivery_email,orders.order_sn,oi.id AS orders_items_id,oi.order_id,oi.product_name,oi.product_id,product.small_img,oi.pay_price,oi.qty,oi.total_amount');
		$order_items_db->join('orders ON orders.id = oi.order_id');
		$order_items_db->join('product ON product.id = oi.product_id');
		$orderInfo = $order_items_db->where('oi.id='.$oiid)->find();
		if(!$orderInfo)
			$this->error(L('_PRODUCT_NO_EXIST_'), url('order/order_purchase_list'));
		
		if($_POST['dosubmit']){
			$post = $_POST;
			$post['order_id'] = $orderInfo['order_id'];
			$post['product_name'] = $orderInfo['product_name'];
			$post['orders_items_id'] = $orderInfo['orders_items_id'];
			$post['order_sn'] = $orderInfo['order_sn'];
			$post['product_id'] = $orderInfo['product_id'];
			$post['user_id'] = $user['id'];
			$post['status'] = 1;
			if($post['addimg']){
				$purchaseImg = cookie('purchaseImg');
				$addimg = explode(',', $post['addimg']);
				$addimgStr = '';
				foreach ($addimg as $imgId) {
					if($purchaseImg[$imgId]){
						$addimgStr .= $purchaseImg[$imgId].',';
                        unset($purchaseImg[$imgId]);
					}
				}
				cookie('purchaseImg',$purchaseImg);
				$post['photo_name'] = trim($addimgStr, ',');
			}
			$pid = OrderModel::insert_purchase_info($post);
			if($pid){
				$this->success(L('_OPERATION_SUCCESS_'), url('user/order_purchase_list'));
			}else{
				$this->error(L('_OPERATION_FAIL_'), url('user/order_purchase_add', array('oiid' => $oiid)));
			}
			
		}else{
			$this->assign('orderInfo', $orderInfo);
			$templatefile = THEMES_PATH.'user/order_purchase_add.phtml';
			$this->assign('templatefile', $templatefile);
			$this->display('usercenter');
		}
	}
	
	//退换货记录列表
	public function order_purchase_list()
	{
		global $user;
		$this->checklogin();
		$pursta = $_GET['purchase_status'];
		$orders_purchase_db = D('orders_purchase');
		$orders_purchase_db->field('id,order_id,product_name,add_time,status,order_sn');
		if($pursta){
			$purchaseList = $orders_purchase_db->where('user_id='.$user['id'].' AND parent_id=0 AND status='.$pursta)->select();
		}else{
			$purchaseList = $orders_purchase_db->where('user_id='.$user['id'].' AND parent_id=0')->select();
		}
		
		$this->assign('purchaseList', $purchaseList);
		$this->assign('pursta', $pursta);
		$templatefile = THEMES_PATH.'user/order_purchase_list.phtml';
		$this->assign('templatefile', $templatefile);
		$this->display('usercenter');		
	}
	
	//查看退换货记录
	public function order_purchase_edit()
	{
		global $user;
		$this->checklogin();
		$orders_purchase_db = D('orders_purchase');
		$pur_id = intval($_GET['pur_id']);
		$purchaseInfo = $orders_purchase_db->find($pur_id);
		if(!$purchaseInfo){
			$this->error(L('_SELECT_NOT_EXIST_'), url('user/order_purchase_list'));
		}
		
		if($_POST['dosubmit']){
			$data = array(
				'parent_id' => $pur_id,
				'description' => trim($_POST['description']),
				'add_time' => time(),
				'user_id' => $user['id'],
			);
			$purid = $orders_purchase_db->add($data);
			$orders_purchase_db->where('id='.$pur_id)->save(array('status' => 1));
			
			if($purid){
				$this->success(L('_OPERATION_SUCCESS_'), url('user/order_purchase_list'));
			}else{
				$this->error(L('_OPERATION_FAIL_'), url('user/order_purchase_edit', array('pur_id' => $pur_id)));
			}
			
		}else{
			$photoList = array();
			if($purchaseInfo['images']){
                $photoList =explode(',', $purchaseInfo['images']);
                foreach ($photoList as $key=>$img) {
                	if(empty($img)) unset($photoList[$key]);
                }
			}
			$orders_purchase_db = D('orders_purchase');
			$mesgList = $orders_purchase_db->field('user_id,add_time,description')->where('parent_id='.$pur_id)->order('id DESC')->select();
			
			$this->assign('mesgList', $mesgList);
			$this->assign('photoList', $photoList);
			$this->assign('purchaseInfo', $purchaseInfo);
			$templatefile = THEMES_PATH.'user/order_purchase_edit.phtml';
			$this->assign('templatefile', $templatefile);
			$this->display('usercenter');
		}
	}
	
	/**
	 * 修改退换货状态
	 */
	public function order_purchase_edit_status()
	{
		$pur_id = intval($_REQUEST['pur_id']);
		$status = intval($_REQUEST['status']);
		$orders_purchase_db = D('orders_purchase');
		$affter = $orders_purchase_db->where('id='.$pur_id)->save(array('status' => $status));
		if($affter){
			$result = array(
				'error' => 0,
				'message' => L(OrderModel::$purchaseStatus[$status]),
			);
		}else{
			$result = array(
				'error' => 1,
				'message' => L('_OPERATION_FAIL_'),
			);
		}
		echo json_encode($result);
	}
	
	/**
	 * 检测是否登录
	 */
	private function checklogin()
	{
		if(! UserModel::logged()){
			$this->error(L('_USER_NO_LOGINED_'), url('user/login'));
		}
	}
    //ajax 检测是否登录 cart/info使用 未登录添加身形专用
    public function checklogin_ajax(){
        if(! UserModel::logged()){
            $info = array(
                'status' => 0,
                'url' =>  url('user/login', array('src' => base64_encode(url('cart/info')))),
            );
        }else{
            $info = array(
                'status' => 1,
            );
        }
       echo json_encode($info);
        exit;
    }
	
	public function validate_email_ajax()
	{
		$email = trim($_REQUEST['email']);
		$email = urldecode($email);
		$user_id = intval($_REQUEST['user_id']);
		import('COM.Validate');
		if(empty($email) || !Validate::email($email)){
			$status = L('_EMAIL_FORMAT_ERROR_');
		}
		elseif(UserModel::validate_email_only($email, $user_id)){
			$status = L('_email_registered_');
		}else{
			$status = true;
		}
		echo json_encode($status);exit;
	}
	public function validate_phone1_ajax()
	{
	    $phone = trim($_REQUEST['phone']);
		$phone = urldecode($phone);
		import('COM.Validate');
		if(empty($phone) || !Validate::registerPhone($phone)){
			$status = L('_PHONE_FORMAT_ERROR_');
		}
		elseif(UserModel::validate_username_only($phone)){
			$status = L('_phone_registered_');
		}else{
			$status = true;
		}
		echo json_encode($status);exit;
	}
	public function validate_phone_ajax()
	{
		$phone = trim($_REQUEST['phone']);
		$phone = urldecode($phone);
		$user_id = intval($_REQUEST['user_id']);
		import('COM.Validate');
		if(empty($phone) || !Validate::registerPhone($phone)){
			$status = L('_PHONE_FORMAT_ERROR_');
		}
		elseif(UserModel::validate_username_only($phone, $user_id)){
			$status = L('_phone_registered_');
		}else{
			$status = true;
		}
		echo json_encode($status);exit;
	}

	//我的红包列表
	Public function bonus_list()
	{
		global $user,$language_id;
		$data = array(
			'docTitle' => L('meta_title_bonus_list'),
			'docKeywords' => L('meta_keywords'),
			'docDescription' => L('meta_description'),
		);
		$this->assign($data);		
		//$this->checklogin();
		if(UserModel::logged()){
		$_SESSION['center_type'] = 12;
		$user_bonus_db = D('user_bonus');
		
		//分页
		$where['user_id'] = $user['id'];
		$user_bonus_db->where($where);
		$count = $user_bonus_db->count();//总记录数
		require THEMES_PATH.'page.php';// 导入分页类
		$Page = new Page($count,20);// 实例化分页类 传入总记录数和每页显示的记录数
		$pageShow = $Page->show();// 分页显示输出
		$this->assign('pageShow', $pageShow);
		
		$user_bonus_db->order('id DESC');
		$user_bonus_db->limit($Page->firstRow.','.$Page->listRows);
		$user_bonus_db->where($where);
		$bonusList02 = $user_bonus_db->select();
		$bonusList = array();
		$i = 0;
		foreach ($bonusList02 as $v){
			$bonus_type_db = D('bonus_type');
			$bonusTypeInfo = $bonus_type_db->field('type_name,type_money,use_start_date,use_end_date,restrict,min_amount')->where('id='.$v['bonus_id'])->find();
			if($bonusTypeInfo['restrict'] > 0){
				/*if($language_id == 4){
					$use_start_date = "无限期";
					$use_end_date = "无限期";
				}else{
					$use_start_date = "unlimited";
					$use_end_date = "unlimited";
				}*/
				$use_end_date = L('indefinite duration');
			
			}else{
				$use_start_date = date('Y-m-d',$bonusTypeInfo['use_start_date']);
				$use_end_date = date('Y-m-d',$bonusTypeInfo['use_end_date']);
				$use_end_date = $use_end_date;
			}
			
			if($bonusTypeInfo['min_amount'] == 0){
				$min_amount = L('unlimited');
			}else{
				$min_amount = currency($bonusTypeInfo['min_amount']);
			}
			$bonusList[$i]['id'] 			 = $v['id'];
			$bonusList[$i]['bonus_sn'] 		 = $v['bonus_sn'];
			$bonusList[$i]['used_time'] 	 = $v['used_time'];
			$bonusList[$i]['type_name'] 	 = $bonusTypeInfo['type_name'];
			$bonusList[$i]['type_money'] 	 = $bonusTypeInfo['type_money'];
			$bonusList[$i]['use_start_date'] = $use_start_date;
			$bonusList[$i]['use_end_date'] 	 = $use_end_date;
			$bonusList[$i]['min_amount'] 	 = $min_amount;
		
			$fortunewheel = D('fortunewheel')->field('is_share')->where(array('user_id'=>$user['id'], 'prize_content'=>$bonusTypeInfo['type_name']))->find();
			if(!$fortunewheel || $fortunewheel['is_share']==1){
				$bonusList[$i]['is_share'] = 1;
			}else{
				$bonusList[$i]['is_share'] = 0; 
			} 
			
			$i++;
		}
		$this->assign('bonusList', $bonusList);

		
		$templatefile = THEMES_PATH.'user/bonus_list.phtml';
		$this->assign('templatefile', $templatefile);
		}else{
		$templatefile = THEMES_PATH.'user/user_login.phtml';
		$this->assign('templatefile', $templatefile);		
		}
		$this->display('usercenter');
	}
	
	public function user_measure()
	{
		global $user;
		$data = array(
			'docTitle' => L('meta_title_user_measure'),
			'docKeywords' => L('meta_keywords'),
			'docDescription' => L('meta_description'),
		);
		$this->assign($data);
		//$this->checklogin();
		if(UserModel::logged()){
		$_SESSION['center_type'] = 10;
		$mid = $_REQUEST['mid'];
		$measureList = D('user_measure')->where('user_id='.$user['id'])->select();
		$this->assign('measureList', $measureList);
		
		$measure_data = '';
		if($mid){
			foreach($measureList as $measure){
				if($measure['id'] == $mid){
						$measure_data = unserialize($measure['measure_data']);
						$measure_name = $measure['measure_name'];
						$measureId = $measure['id'];
				}
			}
		}else{
			$measure_data = unserialize($measureList[0]['measure_data']);
			$measure_name = $measureList[0]['measure_name'];
			$measureId = $measureList[0]['id'];
			
		}
		$this->assign('measure_data', $measure_data);
		$this->assign('measure_name', $measure_name);
		$this->assign('measureId', $measureId);
		
		$templatefile = THEMES_PATH.'user/user_measure.phtml';
		$this->assign('templatefile', $templatefile);
		}else{
		$templatefile = THEMES_PATH.'user/user_login.phtml';
		$this->assign('templatefile', $templatefile);		
		}
		$this->display('usercenter');
	}
	//查看身形数据
	public function user_measure_info()
	{
		global $user;
		$this->checklogin();
		
		
		$templatefile = THEMES_PATH.'user/user_measure_info.phtml';
		$this->assign('templatefile', $templatefile);
		$this->display('usercenter');
	}
	
	public function user_measure_del()
	{
		$mid = intval($_REQUEST['mid']);
		D('user_measure')->delete($mid);
		redirect(url('user/user_measure'));
	}
	
	/**
	 * 编辑订单信息
	 */
	public function edit_order()
	{
		global $user;
		$this->checklogin();
		$post = $_POST;
		$product_amount = isset($post['product_amount']) ? floatval($post['product_amount']) : 0;
		$product_dingjin = isset($post['product_dingjin']) ? floatval($post['product_dingjin']) : (isset($post['dingjin']) ? floatval($post['dingjin']) : 0);
		$payment_fee = isset($post['payment_fee02']) ? floatval($post['payment_fee02']) : 0;
		$shipping_fee = isset($post['shipping_fee']) ? floatval($post['shipping_fee']) : 0;
		$surplus_money = isset($post['surplus_money02']) ? floatval($post['surplus_money02']) : 0;
		$hongbao_money = isset($post['hongbao_money']) ? floatval($post['hongbao_money']) : 0;
		$integral_money = isset($post['integral_money']) ? floatval($post['integral_money']) : 0;
		$hongbao_id = isset($post['hongbao_id']) ? floatval($post['hongbao_id']) : 0;
		
		//添加到订单表
		$order_db = D('orders');
		$post['delivery_cid'] = intval($post['delivery_cid']);
		$post['delivery_pid'] = intval($post['delivery_pid']);
		$data = array(
			'shipping_method' => $post['shipping_method'],
			'payment_fee' => floatval($post['payment_fee']),
			'shipping_fee' => floatval($post['shipping_fee']),
			'delivery_first_name' => trim($post['delivery_first_name']),
			'delivery_last_name' => trim($post['delivery_last_name']),
			'delivery_phone' => trim($post['delivery_phone']),
			'delivery_mobile' => trim($post['delivery_mobile']),
			'delivery_postcode' => trim($post['delivery_postcode']),
			'delivery_cid' => $post['delivery_cid'],
			'delivery_province' => isset($post['delivery_province']) ? trim($post['delivery_province']) : null,
			'delivery_city' =>  isset($post['delivery_city']) ? trim($post['delivery_city']) : null,
			'delivery_address' =>  isset($post['delivery_address']) ? trim($post['delivery_address']) : null,
			'product_dingjin' => $product_dingjin,
			'surplus_money' => $surplus_money,
			'hongbao_money' => $hongbao_money,
			'integral_money' => $integral_money,
		);
		if($post['product_amount']){
			$data['product_amount'] = $post['product_amount'];
		}
		
		if($post['payment_status'] == 4){
			$data['payment_method2'] = $post['payment_method'];
		}else{
			$data['payment_method'] = $post['payment_method'];
		}
		//更新国家
		if($post['delivery_cid']){
			$area_info = SiteModel::get_region_info($post['delivery_cid']);
			if($area_info){
				$data['delivery_country'] = $area_info['name'];
			}
		}
		
		//订单总费用
		$order_amount = $product_amount + $payment_fee + $shipping_fee;
		$data['order_amount'] = $order_amount;
		
		//应付费用
		$pay_amount = $order_amount - $surplus_money - $hongbao_money - $product_dingjin - $integral_money;
		$data['pay_amount'] = $pay_amount;
		
		$result = $order_db->where(array('id' => $post['oid']))->save($data);
		
		
		//扣除会员的余额
		if($surplus_money && $user['id']){
			UserModel::log_account_change($user['id'],(-1)*$surplus_money,0,0,0,L('_ORDER_USE_BALANCE_PAYMENT_').' '.L('_THE_ORDER_NUMBER_IS_').' '.$post['order_sn'],UserModel::ACT_PAY);
		}
		
		//减去会员支付使用的积分
		if($user['user_id'] && $integral_money){
			UserModel::log_account_change($user['user_id'],0,0,0,(-1)*$integral_money,L('_ORDER_REFUND_').' '.L('_THE_ORDER_NUMBER_IS_').' '.$post['order_sn'],UserModel::ACT_REFUND);
		}
		
		
		//更新订单各种费用
		if($post['chima'] != '' && $post['payment_status'] == 0)
			OrderModel::update_order_prices02($post['oid']);
		else
			OrderModel::update_order_prices($post['oid']);
		
		//发送下单邮件
		$orderInfo = OrderModel::get_order_info($post['oid']);
		$mailInstance = new EmailModel();
		$email_template = UserModel::get_email_template_info('orderTradingEmail', $orderInfo['language_id']);
		if($email_template){
			$orderInfo['productList'] = OrderModel::get_order_product_list($post['oid']);
			$content = $mailInstance->replaceMail($email_template['content'], $orderInfo);
			$title = $mailInstance->replaceMail($email_template['title']);
			$mailInstance->sendMail($orderInfo['delivery_email'], $title, $content);
		}
		
		//支付通知邮件
		if(floatval($orderInfo['pay_amount'])==0){
			$email_template = UserModel::get_email_template_info('orderPayEmail', $orderInfo['language_id']);
			if($email_template){
				$content = $mailInstance->replaceMail($email_template['content'], $orderInfo);
				$title = $mailInstance->replaceMail($email_template['title']);
				$mailInstance->sendMail($orderInfo['delivery_email'], $title, $content,'html','bcc');
			}
		}
		
		//删除相应的红包
		if($hongbao_id > 0){
			
			$user_bonus_db = D('user_bonus');
			$data02 = array(
				'bonus_sn' => $post['order_sn'],
				'used_time' => time(),
			);
			$user_bonus_db->where('id='.$hongbao_id)->save($data02);
			
			$bonus_db = D('bonus_type');
			$bonusInfo = $bonus_db->field('id,min_amount,send_start_date,send_end_date')->where('send_type=1')->find();
			//判断红包是否在发送期间
			if(time() >= $bonusInfo['send_start_date'] && time() <= $bonusInfo['send_end_date']){
				if($order_amount > $bonusInfo['min_amount']){
					$data = array(
						'bonus_id' => intval($bonusInfo['id']),
						'bonus_sn' => 0,
						'user_id' => intval($user['id']),
						'used_time' => 0,
						'order_id' => 0,
						'emailed' => 0,//1：已发成功；0未成功
						'time' => time(),
					);
					$user_bonus_id = $user_bonus_db->add($data);	
				}
			}
	
		}
		
		redirect(url('cart/ordersuccee', 'oid='.$post['oid']));
	}
	
	/**
	 * 产品图片关联入库
	 * @param int $pid 产品ID
	 * @param array $post post表单
	 */
	private function insert_photo($pid, $post)
	{
		$photo_ids = $post['photo_name'];
		if($photo_ids){
			$photo_ids = rtrim($photo_ids,',');
			$fids = explode(',', $photo_ids);
			if(count($fids)){
				ProductModel::deleteShaidanPhotoRelation($pid); //删除关联图片
				foreach ($fids as $fid){
					$data = array(
						'fid' => $fid,
						'sid' => $pid,
					);
					$product_photo_relation_db = D('shaidan_photo_relation');
					$product_photo_relation_db->add($data);
				}
			}
		}
	}
	
	public function validate_vcode_ajax()
	{
		$status = true;
		$vcode_name = trim($_REQUEST['vcode']);
		$vcode_value = trim($_REQUEST[$vcode_name]);
		
		if($_SESSION[$vcode_name] != strtolower($vcode_value)){
				$status = (L('_VERIFICATION_ERROR_'));
		}
		
		
		echo json_encode($status);exit;
	}
	
	//晒单列表
	public function shaidan_list()
	{
		global $user;
		$this->checklogin();
		$_SESSION['center_type'] = 15;
		$order_db = D('orders');	
		$ordersList = $order_db->field('id,start_time')->where('order_status=2 AND user_id='.$user['id'].'')->order('id DESC')->select();
		foreach ($ordersList as $v){
			$MyProduct = OrderModel::get_order_product_list($v['id']);
			//echo count($MyProduct)."<br>";
			for($i=0;$i<count($MyProduct);$i++){
				$v['id'] = $MyProduct[$i]['product_id'];
				$MyProductList[$v['id']]['name'] = $MyProduct[$i]['product_name'];
				$MyProductList[$v['id']]['time'] = $v['start_time'];
				$MyProductList[$v['id']]['id'] = $v['id'];
				$modeldb = D('shaidan');
				$model_info = $modeldb->where('product_id='.$v['id'].' AND user_id='.$user['id'])->find();
				$MyProductList[$v['id']]['sid'] = $model_info['id'];
				if($model_info) {
					$MyProductList[$v['id']]['dis'] = 1;
				}else {
					$MyProductList[$v['id']]['dis'] = 0;
				}
			}
		}
		$this->assign('MyProductList', $MyProductList);
		$templatefile = THEMES_PATH.'user/shaidan_list.phtml';
		$this->assign('templatefile', $templatefile);
		$this->display('usercenter');
	}
	
	//添加晒单
	public function add_shaidan()
	{
		global $user;
		$this->checklogin();
		
		$pid = $_GET['id'];
		if(isset($_POST['dosubmit']))
		{
			$post = $_POST;
			//上传图片到产品表
			if(isset($post['focus_photo']) && $post['focus_photo']){
				$img = $post['focus_photo']; //原图
				$dir = dirname($img);
				$img_name = basename($img);
				$post['img'] = $img;
				$post['small_img'] = $dir . '/thumb_' . $img_name; //小图片
			}else{
				$this->error(L('Please upload pictures'));
			}
	
			$pid = ProductModel::updateShaidanInfo($post);
			if(!$pid){
				$this->error(L('_OPERATION_SUCCESS_'), U('user/add_shaidan'));
			}
			
			//图片关联入库
			$this->insert_photo($pid, $post);
			
			$this->success(L('_OPERATION_FAIL_'), U('user/shaidan_list'));
		
		}else{
			
			//统计晒单
			$sd_db = D('shaidan');
			$sdList = $sd_db->field('product_id')->where('user_id='.$user['id'].'')->order('id DESC')->select();
			$shaidan_count = count($sdList);
			
			//统计已购买的商品
			$order_db = D('orders');	
			$ordersList = $order_db->field('id,start_time')->where('order_status=2 AND user_id='.$user['id'].'')->order('id DESC')->select();
			foreach ($ordersList as $v){
				$MyProduct = OrderModel::get_order_product_list($v['id']);
				//echo count($MyProduct)."<br>";
				for($i=0;$i<count($MyProduct);$i++){
					$v['id'] = $MyProduct[$i]['product_id'];
					$MyProductList[$v['id']]['name'] = $MyProduct[$i]['product_name'];
					$MyProductList[$v['id']]['time'] = $v['start_time'];
					$MyProductList[$v['id']]['id'] = $v['id'];
				}
				
			}
			
			$j = $MyProductList;
			if($shaidan_count >= count($j)) {
				$templatefile = THEMES_PATH.'user/add_shaidan02.phtml';
				$this->assign('templatefile', $templatefile);
				$this->display('usercenter');
			}else {
				$MyProductList = UserModel::get_product_list($pid);
				$this->assign('MyProductList', $MyProductList);
				$templatefile = THEMES_PATH.'user/add_shaidan.phtml';
				$this->assign('templatefile', $templatefile);
				$this->display('usercenter');	
			}
		}
		
	}
	/**
	*
	*获取facebook登陆URL
	*@return string($login_url)
	*/
	public function facebook_login(){
		$appid = C('appId');
		$secret = C('secret');
		$config = array(
			'appId'=>$appid,
			'secret'=>$secret,
		);
		Vendor('Facebook.Src.facebook');
		$facebook = new Facebook($config);
		$login_url = $facebook->getLoginUrl(array('scope' => 'email','redirect_uri'=> url('user/facebook_action')));
		return $login_url;
	}

	/**
	*
	*facebook数据处理
	*/
	public function facebook_action(){
		//判断用户是否登陆
		global $user, $language_id;
		$post = $_REQUEST;
		$src = isset($post['src']) ? trim($post['src']) : null;
		$this->assign('src', $src);
		
		$src_login = strstr(base64_decode($src), 'measure/cart');
		$this->assign('src_login', $src_login);
		
		if(UserModel::logged())
		{
			redirect($src ? base64_decode($src) : url('user/center'));
		}
		
		$addUser = D('users');
		//将获取的数据添加到facebook_user中
		$appid = C('appId');
		$secret = C('secret');
		$config = array(
			'appId'=>$appid,
			'secret'=>$secret,
		);
		Vendor('Facebook.Src.facebook');
		$facebook = new Facebook($config);
		$user_id = $facebook->getUser();
		//$user_id=1;//测试数据
		if($user_id){
			//注释部分为测试数据
			//$user_profile['id']=12236154455;
			//$user_profile['email'] = 'wooffox@126.com';
			//$user_profile['username'] = 'qq';
			$user_profile = $facebook->api('/me','GET');
			$where = array(
				'email'=>$user_profile['email']
			);
			$checkUser = $addUser->where($where)->find();
			if(!$checkUser){
				$post['password'] =	substr(md5(mt_rand(0,10000)),0,6);//用户默认密码
				$post['email'] = $user_profile['email'];
				if(!$user_profile['email']){
					echo 'login failed';exit;
				}
				$lastId = UserModel::insert_user($post);
				if($lastId){
					$data = array(
						'face_id'	 =>	$user_profile['id'],
						'face_email' => $user_profile['email'],
						'username'	 => $user_profile['name'],
						'user_id'	 =>	$lastId
					);
					$facebookUser_db = D('facebook_user');
					$addFaceUser = $facebookUser_db->add($data);
					if($addFaceUser){
						$email_template = UserModel::get_email_template_info('facebook', $language_id);
						if($email_template){
							$content = str_replace('{$user_name}', $user_profile['email'], $email_template['content']);
							$content = str_replace('{$user_email}', $user_profile['email'], $content);
							$content = str_replace('{$user_password}',$post['password'], $content);
							$mailInstance = new EmailModel();
							$content = $mailInstance->replaceMail($content);
							$title = $mailInstance->replaceMail($email_template['title']);
							$status = $mailInstance->sendMail_direct($user_profile['email'], $title, $content);
							$user_info = UserModel::get_user_info($lastId);
							if(!$user_info['disabled']){
								$this->error(L('_MEMBER_ACCOUNT_HAS_BEEN_DISABLED_PLEASE_CONTACT_YOUR_ADMINISTRATOR_'));
							}
							session('user_id', $lastId);
						
							//更新用户数据
							UserModel::setLogin($lastId);

							//合并购物车
							CartModel::mergeCart($user['sid']);

							//合并身型数据
							AttributeModel::mergeMeasure($user['sid']);
									
							redirect($src ? base64_decode($src) : url('user/center'));
											
							
						}else{
							echo 'error3';exit;
						}
					}else{
						echo 'error2';dump($data);exit;
					}
					
				}else{
					echo 'error';exit;
				}
				
			}else{
				$user_info = UserModel::get_user_info($checkUser['id']);
				if(!$user_info['disabled']){
					$this->error(L('_MEMBER_ACCOUNT_HAS_BEEN_DISABLED_PLEASE_CONTACT_YOUR_ADMINISTRATOR_'));
				}
				session('user_id', $checkUser['id']);
			
				//更新用户数据
				UserModel::setLogin($checkUser['id']);

				//合并购物车
				CartModel::mergeCart($user['sid']);
				
				//合并身型数据
				AttributeModel::mergeMeasure($user['sid']);				
			
				redirect($src ? base64_decode($src) : url('user/center'));
			}
		}else{
			redirect(url('user/login'));
		}
	}
	//评论图片上传 //退换货
	public function comment_photo_add(){
		//判断用户是否登陆
		global $user, $language_id;
		$list = $_POST['list'];
		$insertId = 0;
		$img = "";
		$thumb = "";
		if(UserModel::logged()){
	        if($_POST['uploadimg']){
	        	$subdir = 'comment/'.date('Y/m/d', time());
	            $file = $this->upload($subdir, 'custom', array(), true);
	            if(isset($file['img'])){
	                //图片存库
				    $photo_db = D('comment_photo');
					$img = $file['img']['savename'];
					$thumb = 'thumb_'.basename($img);
					$img = $data['img'] = UPLOAD_PATH.$img;
					$thumb = $data['thumb'] = UPLOAD_PATH.$subdir.'/'.$thumb;
					$data['user_id'] =$user['id'];
					if(isset($_POST['purchase'])){  //退换货图片不用存表
					    $insertId = rand(1000000,9999999);
					    $purchaseImg = cookie('purchaseImg');
					    $purchaseImg[$insertId] = $img;
					    cookie('purchaseImg', $purchaseImg);
					}else{
						$insertId = $photo_db->add($data);
					}
	            }
	        }
        }
        echo "<script type='text/javascript'>window.parent.photoShow('".$list."','".$insertId."','".$img."','".$thumb."');</script>";
    }

	
	public function qq_login(){
		require_once("./statics/qqConnect/qqConnectAPI.php");
		$qc = new QC();
		$qc->qq_login();		
	}

	public function qq_callback(){
		require_once("./statics/qqConnect/qqConnectAPI.php");
		$qc = new QC();
		$qc->qq_callback();
		//$qc->get_openid();
		$openid = $qc->get_openid();
		
		$addUser = D('users');
		$where = array(
			'qq_openid'=>$openid,
		);
		$checkUser = $addUser->where($where)->find();
		if(!$checkUser){
				$post['password'] =	substr(md5(mt_rand(0,10000)),0,6);//用户默认密码
				$post['email'] = 'qq'.date('ymdHis',time()).mt_rand(100,999).'@qq.com';
				//  新用户充值送100活动
				//$post['user_money']=100;
				
				$lastId = UserModel::insert_user($post);
				
				if($lastId){
					//绑定qq_openid
					$addUser->where(array('id'=>$lastId))->save(array('qq_openid'=>$openid));
					
					session('user_id', $lastId);
				
					//更新用户数据
					UserModel::setLogin($lastId);

					//合并购物车
					CartModel::mergeCart($user['sid']);

					//合并身型数据
					AttributeModel::mergeMeasure($user['sid']);
                    if(cookie("action_measure")=="measure"){
                        cookie("action_measure",null);
                        redirect(url('measure/measure'));
                    }else {
                        redirect($src ? base64_decode($src) : url('user/center'));
                    }
				}else{
					echo 'error';exit;
				}		
		}else{
			$user_info = UserModel::get_user_info($checkUser['id']);
			if(!$user_info['disabled']){
				$this->error(L('_MEMBER_ACCOUNT_HAS_BEEN_DISABLED_PLEASE_CONTACT_YOUR_ADMINISTRATOR_'));
			}
			session('user_id', $checkUser['id']);
		
			//更新用户数据
			UserModel::setLogin($checkUser['id']);

			//合并购物车
			CartModel::mergeCart($user['sid']);
			
			//合并身型数据
			AttributeModel::mergeMeasure($user['sid']);
            if(cookie("action_measure")=="measure"){
                cookie("action_measure",null);
                redirect(url('measure/measure'));
            }else {
                redirect($src ? base64_decode($src) : url('user/center'));
            }
		}			
	}    
}